#include "myhead.h"

// 定义结构体来表示单链表
struct singlelist
{
    char name[20]; // 存放人的名字，每个结构体变量代表一个学生
    int age;
    float score;
    struct singlelist *next;
};

// 链表的初始化--》初始化头节点
struct singlelist *list_init()
{
    struct singlelist *head = malloc(sizeof(struct singlelist));
    head->next = NULL; // 目前还不知道下一个节点是谁
    bzero(head->name, 20);
    strcpy(head->name,"蔡徐坤");
    head->age = 18;
    head->score = 2.5;
    return head;
}

// 创建新的节点
struct singlelist *list_create_node(char name[], int age, int score)
{
    struct singlelist *node = malloc(sizeof(struct singlelist));
    strcpy(node->name, name);
    node->age = age;
    node->score = score;
    node->next = NULL;
    return node;
}

/*
    把newnode代表的节点插入到head代表的链表的尾部
*/
int list_insert_tail(struct singlelist *head, struct singlelist *node)
{
    struct singlelist *p = head;
    for (; p->next != NULL; p = p->next)
        ;
    node->next = NULL;
    p->next = node;
}

// 从中间插入节点
int list_insert_between(struct singlelist *oldcode, struct singlelist *newcode)
{
    newcode->next = oldcode->next;
    oldcode->next = newcode;
}

//遍历所有节点
void showing(struct singlelist *head)
{
    struct singlelist *p = head;
    while (p != NULL)
    {
        printf("\n学生姓名:%-15s 年龄:%-10d 分数:%-10f\n", p->name, p->age, p->score);
        p = p->next;
    }
}
    int main()
    {
        int i;
        struct singlelist *head = list_init();
        struct singlelist *node1, *node2, *node3, *node4, *node5;
    
        //创建新的节点
        node1 = list_create_node("郑安派", 18, 99);
        node2 = list_create_node("孙辉", 20, 89);
        node3 = list_create_node("李晗", 24, 68);
        node4 = list_create_node("黄正🐏", 21, 89);
        node5 = list_create_node("钟康", 20, 94);
        // 尾插几个节点
        list_insert_tail(head, node1);
        list_insert_tail(head, node2);
        list_insert_tail(head, node3);
        list_insert_tail(head, node4);
        list_insert_tail(head, node5);
        
        printf("============================添加前============================");
        //遍历一遍防止数据未写入
        showing(head);
        
        printf("============================添加后============================");
        //创建新的节点
        struct singlelist* newnode = list_create_node("丁真",18,99);
        //把丁真插在孙辉后面
        list_insert_between(node3,newnode);
        //再次遍历
        showing(head);

        return 0;

    }
